<template>
  <div style="padding: 20px">
    <el-row>
      <el-col style="width: 100%">
        <div style="width: 70%;margin: 0 auto">
          <el-steps :active="step" align-center finish-status="success">
            <el-step title="基本信息"></el-step>
            <el-step title="规格参数"></el-step>
            <el-step title="销售属性"></el-step>
            <el-step title="商品描述"></el-step>
            <el-step :status="stepStatus" title="保存完成"></el-step>
          </el-steps>
        </div>
      </el-col>
      <el-col :span="24" v-show="step === 0">
        <el-card class="box-card" style="width:70%;margin:20px auto">
          <el-form ref="spuBaseForm" :model="spu" label-width="120px" :rules="spuBaseInfoRules">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="spu.name" placeholder="请输入商品名称"></el-input>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="选择分类" prop="categoryId">
                  <category-selector :category-path.sync="categoryPath"></category-selector>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排序" prop="sort">
                  <el-input-number v-model.number="spu.sort" :min="0" placeholder="输入排序"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="选择品牌" prop="brandId" v-if="this.categoryPath && this.categoryPath.length === 3">
              <brand-select :brand-id.sync="spu.brandId" :category-id="this.categoryPath[this.categoryPath.length - 1]"></brand-select>
            </el-form-item>
            <el-form-item label="商品重量(Kg)" prop="weight">
              <el-input-number v-model.number="spu.weight" :min="0" :precision="2" :step="0.1" placeholder="输入重量"></el-input-number>
            </el-form-item>
            <el-form-item label="商品图集" prop="images">
              <image-library type="list" v-model="spu.images"></image-library>
            </el-form-item>
            <el-form-item>
              <el-button type="success" size="mini" style="float: right" @click="collectSpuBaseInfo">
                设置基本参数
                <i class="el-icon-right"/>
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="24" v-show="step === 1">
        <el-card class="box-card" style="width:70%;margin:20px auto">
          <el-row>
            <el-col style="margin-top: 10px" :span="24" v-for="(group,gIdx) in attrInfo.baseAttrGroups" :key="group.attrGroupId">
              <el-card shadow="never">
                <div slot="header" class="clearfix">
                  <span>{{ group.name }}</span>
                </div>
                <div style="display: flex">
                  <div
                    style="width: 300px"
                    v-for="(attr,sIdx) in group.attrs"
                    :key="attr.id">
                    {{ attr.name }}
                    <el-checkbox
                      v-model="attrInfo.baseAttrs[gIdx][sIdx].quickShow"
                      :true-label="1"
                      :false-label="0"
                    >列表展示
                    </el-checkbox>
                    <el-checkbox-group :max="attrInfo.baseAttrs[gIdx][sIdx].valueType === 1 ? 1 : 999" v-model="attrInfo.baseAttrs[gIdx][sIdx].attrValues">
                      <el-checkbox
                        style="width: 100%"
                        v-for="(val,vIdx) in attr.optionalValue"
                        :key="vIdx"
                        :label="val"></el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <div style="margin-top: 20px;padding-bottom: 10px;float: right">
            <el-button type="primary" size="mini" icon="el-icon-back" @click="step = 0">上一步</el-button>
            <el-button type="success" size="mini" @click="generateSaleAttrs">设置销售属性<i class="el-icon-right"/></el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24" v-show="step === 2">
        <el-card class="box-card" style="width:90%;margin:20px auto">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>选择销售属性</span>
              <el-form ref="saleForm" :model="spu">
                <el-form-item
                  :label="attr.name"
                  v-for="(attr,sIdx) in attrInfo.saleAttrs"
                  :key="attr.id"
                >
                  <el-checkbox-group v-model="attrInfo.checkedSaleAttrs[sIdx].attrValues">
                    <el-checkbox
                      :label="val"
                      v-for="val in attrInfo.saleAttrs[sIdx].optionalValue"
                      :key="val"
                    ></el-checkbox>
                    <div style="margin-left:20px;display:inline">
                      <el-button
                        v-show="!inputVisible[sIdx].view"
                        class="button-new-tag"
                        size="mini"
                        @click="showInput(sIdx)"
                      >+新增
                      </el-button>
                      <el-input
                        v-show="inputVisible[sIdx].view"
                        v-model="inputValue[sIdx].val"
                        :ref="'saveTagInput' + sIdx"
                        size="mini"
                        style="width:150px"
                        @keyup.enter.native="handleInputConfirm(sIdx)"
                        @blur="handleInputConfirm(sIdx)"
                      ></el-input>
                    </div>
                  </el-checkbox-group>
                </el-form-item>
              </el-form>
              <el-button
                :loading="genSkuLoading"
                size="mini" type="primary"
                icon="el-icon-coordinate"
                @click="confirmGenSku">生成SKU信息</el-button>
              <el-table v-if="this.spu.skus" :data="spu.skus" style="width: 100%;margin-top:10px">
                <el-table-column align="center" label="属性组合">
                  <el-table-column
                    align="center"
                    :label="item.attrName"
                    v-for="(item,index) in attrInfo.tableHeader"
                    :key="item.id"
                  >
                    <template slot-scope="scope">
                      <span style="margin-left: 10px">{{ scope.row.attrs[index].attrValue }}</span>
                    </template>
                  </el-table-column>
                </el-table-column>
                <el-table-column label="商品名称" align="center" prop="skuName">
                  <template slot-scope="scope">
                    <el-input size="mini" v-model="scope.row.name"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="价格" align="center" prop="price">
                  <template slot-scope="scope">
                    <el-input type="number" size="mini" v-model="scope.row.price"></el-input>
                  </template>
                </el-table-column>
                <el-table-column width="170" align="center" label="SKU封面" prop="price">
                  <template slot-scope="scope">
                    <image-library :width="80" :height="80" :num="1" v-model="scope.row.cover"></image-library>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div style="margin-top: 20px;padding-bottom: 10px;float: right">
              <el-button type="primary" size="mini" icon="el-icon-back" @click="step = 1">上一步</el-button>
              <el-button type="success" size="mini" @click="fillDescription">设置商品描述<i class="el-icon-right"/></el-button>
            </div>
          </el-card>
        </el-card>
      </el-col>
      <el-col :span="24" v-show="step === 3">
        <el-card style="width:90%;margin:20px auto">
          <editor :minHeight="400" v-model="spu.detail"></editor>
          <div style="margin-top: 20px;padding-bottom: 10px;float: right">
            <el-button type="primary" size="mini" icon="el-icon-back" @click="step = 2">上一步</el-button>
            <el-button type="success" size="mini" @click="submitSkus">发布商品<i class="el-icon-right"/></el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24" v-show="step === 4">
        <el-card class="box-card" style="width:90%;margin:20px auto">
          <template v-if="publishStatus === 1">
            <el-result icon="success" title="商品发布成功">
              <template slot="extra">
                <el-button type="primary" icon="el-icon-check" size="mini" @click="backSpuList">返回商品列表</el-button>
              </template>
            </el-result>
          </template>
          <template v-if="publishStatus === 0">
            <el-result icon="info" title="正在发布商品" subTitle="发布时间与 SKU 数量成正比，请等待">
            </el-result>
          </template>
          <template v-if="publishStatus === -1">
            <el-result icon="error" title="商品发布失败" subTitle="商品发布失败">
              <template slot="extra">
                <el-button type="primary" size="mini" icon="el-icon-refresh-left" @click="step = 3">返回重试</el-button>
              </template>
            </el-result>
          </template>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import CategorySelector from '../../common/categorySelector.vue'
import BrandSelect from '../../common/brandSelect.vue'
import { getSpuById, getSpuSaleAttr, spuSave, spuUpdate } from '@/api/product/spu'
import { getAttrGroupWithAttr } from '@/api/product/attrGroup'
import { baseAttrListBySpuId, saleAttrListByCategoryId } from '@/api/product/attr'
import ImageLibrary from '@/components/ImageLibrary/index.vue'
import { listSpuImage } from '@/api/product/spuImage'
import { getSpuDetail } from '@/api/product/spuDetail'
import { listSkuBySpuId } from '@/api/product/sku'

export default {
  components: { ImageLibrary, CategorySelector, BrandSelect },
  data() {
    return {
      categoryPath: [],
      genSkuLoading: false,
      step: 0,
      stepStatus: 'wait',
      spu: {
        status: 0,
        baseAttrs: [],
        skus: []
      },
      spuBaseInfoRules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择一个分类', trigger: 'blur' }
        ],
        // brandId: [
        //   { required: true, message: '请选择一个品牌', trigger: 'blur' }
        // ],
        images: [
          { required: true, message: '请上传商品图片集', trigger: 'blur' }
        ]
      },
      attrInfo: {
        // 基础属性分组
        baseAttrGroups: [],
        // 基础属性
        baseAttrs: [],
        // 基础属性组
        saleAttrs: [],
        // 销售属性
        checkedSaleAttrs: [],
        tableHeader: [],
        memberLevels: []
      },
      inputVisible: [],
      // 商品发布状态
      publishStatus: 0,
      inputValue: []
    }
  },
  watch: {
    categoryPath(val) {
      this.spu.categoryId = val[val.length - 1]
    }
  },
  created() {
    let spuId = this.$route.query.spuId
    if (spuId) {
      this.fillSpuInfo(spuId)
    }
  },
  methods: {
    backSpuList() {
      this.$router.push({ path: '/commodity/commodity' })
    },
    fillSpuInfo(spuId) {
      getSpuById(spuId).then(res => {
        if (res.success) {
          this.spu = { ...res.data }
          let [lv1, lv2, lv3] = res.data.categoryPathIdStr.split(',')
          this.categoryPath = [lv1, lv2, lv3]
          listSpuImage(spuId).then(res => {
            if (res.success) {
              this.spu.images = res.data.map(item => item.imgUrl)
              this.$forceUpdate()
            }
          })
          this.spu.bounds = {
            buyBounds: 0,
            growBounds: 0
          }
        }
      })
    },
    fillDescription() {
      if (this.spu.id) {
        getSpuDetail(this.spu.id).then(res => {
          if (res.success) {
            this.spu.detail = res.data.detail
            this.$forceUpdate()
          }
        })
      }
      this.step = 3
    },
    showInput(idx) {
      this.inputVisible[idx].view = true
    },
    handleInputConfirm(idx) {
      debugger
      let inputValue = this.inputValue[idx].val
      if (inputValue && inputValue.length > 0) {
        this.attrInfo.saleAttrs[idx].optionalValue.push(inputValue)
      }
      this.inputVisible[idx].view = false
      this.inputValue[idx].val = ''
    },
    collectSpuBaseInfo() {
      this.$refs.spuBaseForm.validate(valid => {
        if (valid) {
          this.step = 1
          this.showBaseAttrs()
        } else {
          return false
        }
      })
    },
    generateSaleAttrs() {
      // 处理上一步保存的基础属性
      this.spu.baseAttrs = []
      this.attrInfo.baseAttrs.forEach(item => {
        item.forEach(attr => {
          let { id, attrValues, quickShow } = attr
          this.spu.baseAttrs.push({ id, attrValues, quickShow })
        })
      })
      this.step = 2
      this.showSaleAttr()
      if (this.spu.id) {
        listSkuBySpuId(this.spu.id).then(res => {
          if (res.success) {
            this.spu.skus = res.data
          }
        })
      }
    },

    confirmGenSku() {
      if (this.spu.id) {
        this.$confirm('重新生成sku信息会删除原有sku信息，确定进行此操作吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.generateSkus()
          this.spu.regenerateSku = true
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消生成'
          });
        });
      } else {
        this.generateSkus()
      }
    },

    generateSkus() {
      this.genSkuLoading = true
      let selectValues = []
      this.spu.skus = []
      this.attrInfo.tableHeader = []
      this.attrInfo.checkedSaleAttrs.forEach(item => {
        if (item.attrValues.length > 0) {
          selectValues.push(item.attrValues)
          this.attrInfo.tableHeader.push(item)
        }
      })

      let descartes = this.descartes(selectValues)
      let skus = []
      descartes.forEach(item => {
        let attrArray = []
        item.forEach((e, index) => {
          let saleAttrItem = {
            id: this.attrInfo.tableHeader[index].id,
            attrName: this.attrInfo.tableHeader[index].attrName,
            attrValue: e
          }
          attrArray.push(saleAttrItem)
        })

          skus.push({
            attrs: attrArray,
            name: this.spu.name + ' ' + item.join(' '),
            price: 0,
            cover: '',
            descar: item,
            fullCount: 0,
            discount: 0,
            countStatus: 0,
            fullPrice: 0.0,
            reducePrice: 0.0,
            priceStatus: 0,
          })
      })
      this.spu.skus = skus
      this.genSkuLoading = false
    },

    showSaleAttr() {
      saleAttrListByCategoryId(this.spu.categoryId).then(res => {
        this.attrInfo.saleAttrs = res.data
        res.data.forEach(item => {
          this.attrInfo.checkedSaleAttrs.push({
            id: item.id,
            attrValues: [],
            attrName: item.name
          })
          this.inputVisible.push({ view: false })
          this.inputValue.push({ val: '' })
        })
        if (this.spu.id) {
          getSpuSaleAttr(this.spu.id).then(res => {
            if (res.success) {
              let spuSaleAttr = res.data
              // 回显自定义的属性 - 如果要删除则在外方删除 sku 即可
              this.attrInfo.saleAttrs.forEach(saleAttrItem => {
                let find = spuSaleAttr.find(e => saleAttrItem.id === e.attrId)
                if (find) {
                  let attrs = find.attrValues.split(',')
                  attrs.forEach(e => {
                    if (saleAttrItem.optionalValue.indexOf(e) === -1) {
                      saleAttrItem.optionalValue.push(e)
                    }
                  })
                }
              })
              this.attrInfo.checkedSaleAttrs.forEach(checkedItem => {
                let find = spuSaleAttr.find(e => checkedItem.id === e.attrId)
                if (find) {
                  // 已选中回显
                  checkedItem.attrValues.push(...find.attrValues.split(','))
                }
              })

              this.attrInfo.tableHeader = spuSaleAttr.map(item => {
                return {
                  id: item.id,
                  attrValues: item.attrValues.split(','),
                  attrName: item.attrName
                }
              })
            }
          })
        }
      })
    },
    showBaseAttrs() {
      getAttrGroupWithAttr(this.spu.categoryId).then(res => {
        if (res.success) {
          res.data.forEach(item => {
            let attrArray = []
            item.attrs.forEach(attr => {
              attrArray.push({
                id: attr.id,
                attrValues: [],
                quickShow: attr.quickShow,
                valueType: attr.valueType
              })
            })
            this.attrInfo.baseAttrs.push(attrArray)
          })
        }
        this.attrInfo.baseAttrGroups = res.data
        if (this.spu.id) {
          baseAttrListBySpuId(this.spu.id).then(res => {
            if (res.success) {
              let data = res.data
              if (this.attrInfo.baseAttrs) {
                this.attrInfo.baseAttrs.forEach(item => {
                  item.forEach(e => {
                    e.quickShow = 0
                    let find = data.find(item => item.attrId === e.id)
                    if (find) {
                      e.attrValues.push(...find.attrValue)
                      e.quickShow = find.quickShow
                    }
                  })
                })
              }
            }
          })
        }
      })
    },

    submitSkus() {
      this.$confirm('将要提交商品数据，提交需要一小段时间，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.step = 4
        this.stepStatus = 'process'
        this.publishStatus = 0
        if (!this.spu.id) {
          spuSave(this.spu).then(res => {
            if (res.success) {
              this.publishStatus = 1
              this.stepStatus = 'success'
              this.$message.success('新增商品成功')
            } else {
              this.stepStatus = 'error'
              this.publishStatus = -1
            }
          })
        } else {
          spuUpdate(this.spu).then(res => {
            if (res.success) {
              this.publishStatus = 1
              this.stepStatus = 'success'
              this.$message.success('商品信息已更新')
            } else {
              this.publishStatus = -1
              this.stepStatus = 'error'
            }
          })
        }
      }).catch(e => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },

    descartes(list) {
      if (list.length === 0) {
        return []
      }
      let descartesList = []
      this.backtrace(list, 0, [], descartesList)
      return descartesList
    },
    backtrace(list, level, arr, descartesList) {
      if (arr.length === list.length) {
        descartesList.push(Object.assign([], arr))
        return
      }
      let itemList = list[level]
      for (let i = 0; i < itemList.length; i++) {
        arr.push(itemList[i])
        this.backtrace(list, ++level, arr, descartesList)
        // 回溯
        arr.pop()
        level--
      }
    }
  },
}
</script>
<style scoped>
</style>
